import {
  GetBySubmoduleIdAndKeywordId,
  GetSelectItemBySelectType,
  TaskGetDetailSortNo,
  TaskDetailGetPage,
  GetTaskDetailById,
  TaskDeleteDetail,
  TaskDetailUpdate,
  TaskDetailSaev
} from "@/api/teacher/task";
import qs from "qs";
import { ref, reactive, nextTick, watch, onBeforeUnmount, computed } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { emitter } from "@/utils/mitt";
import { cloneDeep } from "@pureadmin/utils";
import {
  usetaskPass,
  taskFormDetiall,
  taskTableDetiall,
  TaskDetailList
} from "@/store/modules/taskPass";
export function useDetail() {
  const [usetaskPass_, taskDetiall_Form, taskDetiall_Table, TaskDetailList_] = [
    usetaskPass(),
    taskFormDetiall(),
    taskTableDetiall(),
    TaskDetailList()
  ];
  const UpedateRef = ref();
  const MyOrCredit = ref(false)
  const taskDetailKeywordInput = ref([]) //用来存储捅同时存在的keyword
  const showTable = ref<boolean>(false); //table类型
  const showForm = ref<boolean>(false); //form类型
  const showNoOperation = ref<boolean>(false);//操作就可以得分
  const loading = ref<boolean>(false);
  const dataList = ref<any>([]);
  const updatePanelVisible = ref(false);
  const loadingTitle = ref(undefined);
  const modelItemList = ref<any>([]);
  const _propsDetails = ref<Object | any>({});
  const GetTaskDetailKeywordForm = ref<any>();
  const GetTaskDetailKeywordTable = ref<any>();
  const GetTaskAllDetailKeywordsForm = ref<any>();
  const GetTaskAllDetailKeywordsTable = ref<any>();
  const _disabled = ref<boolean>(true); // 禁用操作菜单
  const noKeywords = ref<boolean>(false) //展示没有keyWord
  const cloneDeepLinkData = ref({}) //存放联动数据
  interface PropDetails {
    id: Number;
    planId: Number;
    taskId: Number;
    submoduleId: String;
    score: Number;
    selectKeywordId: String;
    sortNo: Number;
  }
  // 分页
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 监听任务明细列表
  watch(TaskDetailList_, newval => {
    dataList.value = newval.data; // 任务明细列表
    pagination.total = newval.total;
    pagination.pageSize = newval.pageSize;
    pagination.currentPage = newval.currentPage;
  });

  // 校验 添加任务详情
  const rules = {
    submoduleId: [
      {
        required: true,
        message: "请选择操作菜单！",
        trigger: ["blur", "change"]
      }
    ],
    score: [
      {
        validator: (rule: any, value: any, callback: () => void) => {
          if (Number(value) <= 0) {
            return callback(new Error("分值必须大于0！"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
      // {
      //   required: true,
      //   message: "请输入分值！",
      //   trigger: ["blur", "change"]
      // }
    ],
    taskKeywrodList: [
      {
        validator: (rule: any, value: any, callback: () => void) => {
          callback();
        },
        trigger: "blur"
      }
    ]
  };

  // 任务明细
  const forms = reactive<PropDetails | any>({
    taskDetailId: 0,
    planId: null, // 计划id
    taskId: null, // 任务id
    submoduleId: null, // 子模块Id
    score: null, //score 分数
    selectKeywordId: null, // 关键字
    sortNo: 0, // 明细序号
    isTemplate: 0,
    isDelete: 0,
    isEdit: 0,
    taskKeywrodList: []
  });

  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "操作菜单",
      prop: "submoduleName",
      minWidth: 300
    },
    {
      label: "分值",
      prop: "score",
      minWidth: 300
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  // 修改与查看任务明细
  function DetailsUpdate(row: any | undefined) {
    // 先选中任务列表
    if (!usetaskPass_.data.isEdit && usetaskPass_.data.isTemplate && !row) {
      ElMessage.warning("暂无添加/编辑权限");
      return
    }
    if (usetaskPass_.data?.taskId) {
      updatePanelVisible.value = true;
      GetSubmoduleByModuleId(usetaskPass_.data);
    } else {
      ElMessage.warning("请选择任务列表！");
      return;
    }

    if (row) {
      loadingTitle.value = "修改明细";
      _disabled.value = true;
      nextTick(() => {
        forms.taskDetailId = row.taskDetailId; //自增 0
        forms.planId = row.planId;
        forms.taskId = row.taskId;
        forms.submoduleId = row.submoduleName;
        forms.selectKeywordId = row.selectKeywordId;
        forms.sortNo = row.sortNo;
        forms.isTemplate = row.isTemplate;
        GetTaskDetailKeywords_submoduleId(row);
        forms.score = row.score;
        forms.isEdit = row.isEdit;
        forms.isDelete = row.isDelete;
      });
    } else {
      forms.taskDetailId = 0;
      forms.isEdit = 0;
      forms.isTemplate = 0;
      _disabled.value = false;
      loadingTitle.value = "添加明细";
    }
    // 获取操作菜单列表
  }

  // 监听页面-- 分页显示数量
  function handleSizeChange() {
    onSearch(usetaskPass_.data);
  }

  // 分页
  function handleCurrentChange() {
    onSearch(usetaskPass_.data);
  }

  // 关闭
  function ClosePanelVisible(row: FormInstance | undefined) {
    updatePanelVisible.value = false;
    GetTaskDetailKeywordForm.value = undefined;
    GetTaskDetailKeywordTable.value = undefined;
    GetTaskAllDetailKeywordsForm.value = undefined;
    GetTaskAllDetailKeywordsTable.value = undefined;
    taskDetiall_Form.data = [];
    taskDetiall_Table.data = [];
    showForm.value = false
    showTable.value = false
    showNoOperation.value = false
    row.resetFields();
    setTimeout(() => { MyOrCredit.value = !MyOrCredit.value; }, 200)
  }

  // 获取任务详情列表
  async function onSearch(data: any) {
    const tow = {
      pageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      taskId: data.taskId
    };
    const respone = await TaskDetailGetPage(qs.stringify(tow));
    loading.value = true;
    if (respone.success) {
      loading.value = false;
      dataList.value = respone.data?.list;
    }
  }

  // 根据操作菜单获取关键词table头部
  async function GetTaskDetailKeywords_submoduleId(event: { moduleId: any; keywordId: any; selectKeywordId: any; taskDetailId: any; submoduleName: any, submoduleNo: any, }) {
    const data = {
      moduleId: event.moduleId,
      submoduleName: event.submoduleNo
    };
    showForm.value = false
    showTable.value = false
    showNoOperation.value = false
    taskDetiall_Form.data = [];
    taskDetiall_Table.data = [];
    taskDetailKeywordInput.value = []
    const respone = await GetBySubmoduleIdAndKeywordId(qs.stringify(data));
    if (respone.success) {
      if (respone?.data.length == 0) {
        showNoOperation.value = true
      } else {
        respone.data.forEach(item => {
          if (item.answerType == 1) {
            showTable.value = true
            nextTick(() => {
              GetTaskDetailKeywordTable.value = item
            })
          }
          if (item.answerType == 2) {
            showForm.value = true
            nextTick(() => {
              GetTaskDetailKeywordForm.value = item
            })
          }
          taskDetailKeywordInput.value.push({
            selectKeywordId: item.selectKeywordId,
            type: item.answerType
          })
        })
      }
      GetTaskAllDetailKeywords(event.taskDetailId);
      // 给table页面
    } else {
      ElMessage.error(respone.msg)
    }

    emitter.emit('closeForm')
    if (!event.taskDetailId) {
      forms.score = null
    }
  }
  // 添加任务详情-明细
  async function updateTask(row: FormInstance | undefined) {
    if (showForm.value) {
      emitter.emit("SAVE_CrediTable");
    }
    (row as any).validate(async (valid: any) => {
      if (!valid) return;
      let respone = reactive<any>({}); // 提交后返回的值
      // 是否是征信大数据
      // 设置默认值
      const defaultValues = {
        examinationPaperId: 0
      };
      // 判断是否有 taskDetailId 字段
      const TaskID = forms.taskDetailId
        ? await GetTaskDetailById(forms.taskDetailId)
        : null;
      let newArray = []
      let correctAnswerStr = []
      //只是同时存在的
      if (showForm.value && showTable.value) {
        if (taskDetiall_Table.data.length == 0) {
          ElMessage.warning('请至少填写一条数据')
          return
        }
        correctAnswerStr = GetTaskDetailKeywordForm.value.keyValues.map((el, index) => {
          el.value = taskDetiall_Form.data[0]['value' + Number(index + 1)] || ''
          return el
        });
        let newArray1 = taskDetiall_Form.data.map(el => {
          const MultipleSelectArr = []
          GetTaskDetailKeywordForm.value.keyValues.forEach((a, index) => {
            el['value' + Number(index + 1)] = JSON.stringify({
              key: a.key,
              value: el['value' + Number(index + 1)] || ''
            })
          })
          //多选和区间暂不处理
          for (let key in el) {
            if (key.includes('MultipleSelectValue')) {
              const extractedKey = key.split("MultipleSelectValue")[1];
              MultipleSelectArr.push({
                key: extractedKey,
                value: Array.isArray(el[key]) ? el[key].join("、") : el[key]
              });
            }
          }
          const jsonString = JSON.stringify(MultipleSelectArr);
          if (MultipleSelectArr.length) {
            return { ...el, ['MultipleSelectValue']: jsonString };
          } else {
            return el
          }
        })
        newArray1.forEach(item => {
          newArray.push(item)
        })
        let newArray2 = taskDetiall_Table.data.map(el => {
          //多选和区间暂不处理
          const MultipleSelectArr = []
          // console.log(taskDetiall_Table.data);

          for (let key in el) {
            if (key.includes('MultipleSelectValue')) {
              const extractedKey = key.split("MultipleSelectValue")[1];
              MultipleSelectArr.push({
                key: extractedKey,
                value: Array.isArray(el[key]) ? el[key].join("、") : el[key]
              });
            }
          }
          const jsonString = JSON.stringify(MultipleSelectArr);
          if (MultipleSelectArr.length) {
            return { ...el, ['MultipleSelectValue']: jsonString };
          } else {
            return el
          }
        });
        newArray2.forEach(item => {
          newArray.push(item)
        })
      }
      //这是有关键字且是form类型
      if (showForm.value && !showTable.value) {
        correctAnswerStr = GetTaskDetailKeywordForm.value.keyValues.map((el, index) => {
          el.value = taskDetiall_Form.data[0]['value' + Number(index + 1)] || ''
          return el
        });
        newArray = taskDetiall_Form.data.map(el => {
          const MultipleSelectArr = []
          GetTaskDetailKeywordForm.value.keyValues.forEach((a, index) => {
            if (el['value' + Number(index + 1)] !== '' && !!el['value' + Number(index + 1)]) {
              el['value' + Number(index + 1)] = JSON.stringify({
                key: a.key,
                value: el['value' + Number(index + 1)] || ''
              })
            }
          })
          //多选和区间暂不处理
          for (let key in el) {
            if (key.includes('MultipleSelectValue')) {
              const extractedKey = key.split("MultipleSelectValue")[1];
              MultipleSelectArr.push({
                key: extractedKey,
                value: Array.isArray(el[key]) ? el[key].join("、") : el[key]
              });
            }
          }
          const jsonString = JSON.stringify(MultipleSelectArr);
          if (MultipleSelectArr.length) {
            return { ...el, ['MultipleSelectValue']: jsonString };
          } else {
            return el
          }
        })
      }

      //有关键字是table
      if (!showForm.value && showTable.value) {
        if (taskDetiall_Table.data.length == 0) {
          ElMessage.warning('请至少填写一条数据')
          return
        }
        newArray = taskDetiall_Table.data.map(el => {
          //多选和区间暂不处理
          const MultipleSelectArr = []
          // console.log(taskDetiall_Table.data);

          for (let key in el) {
            if (key.includes('MultipleSelectValue')) {
              const extractedKey = key.split("MultipleSelectValue")[1];
              MultipleSelectArr.push({
                key: extractedKey,
                value: Array.isArray(el[key]) ? el[key].join("、") : el[key]
              });
            }
          }
          const jsonString = JSON.stringify(MultipleSelectArr);
          if (MultipleSelectArr.length) {
            return { ...el, ['MultipleSelectValue']: jsonString };
          } else {
            return el
          }
        });
      }
      // console.log(newArray);

      // 根据条件设置表单字段
      const forms_ = {
        ...forms,
        planId: usetaskPass_.data.planId,
        taskId: usetaskPass_.data.taskId,
        submoduleId: TaskID?.data.submoduleId ?? forms.submoduleId.submoduleId,
        selectKeywordId: forms.submoduleId.keywordId,
        datagrId: forms.submoduleId.datagrId || "",
        table: newArray.length,
        ...defaultValues,
        ...(TaskID && {
          submoduleId: TaskID.data.submoduleId,
          examinationPaperId: 1
        }),
        taskDetailKeywordInput: taskDetailKeywordInput.value
      };
      forms_.taskKeywrodList = newArray.length == 0 ? [{
        taskkeywordId: "",
        examinationPaperId: "",
        planId: usetaskPass_.data.planId,
        taskId: usetaskPass_.data.taskId,
        taskDetailId: "",
        datagrId: "",
        multipleSelectValue: "",
        type: 3,
        correctAnswerStr: "",
        multistageChangeKeywordId: "",
        multistageChangeKeywordType: ""
      }] : newArray;
      if (newArray.length == 0) {
        forms_.type = 3
      }
      // 目前只想到这种赋值
      if (newArray.length !== 0) {
        // 同时存在的
        if (showForm.value && showTable.value) {
          forms_.taskKeywrodList[0].type = 2
          const valueKeys = Object.keys(taskDetiall_Form.data[0]).filter(key => /^value\d+$/.test(key));

          valueKeys.sort((a, b) => {
            const numA = parseInt(a.replace("value", ""));
            const numB = parseInt(b.replace("value", ""));
            return numA - numB;
          });
          let formResult = []
          valueKeys.forEach(key => {
            if (taskDetiall_Form.data[0][key] == '') delete taskDetiall_Form.data[0][key]
            if (taskDetiall_Form.data[0][key] == null || taskDetiall_Form.data[0][key] == undefined || taskDetiall_Form.data[0][key] == "") return;
            const value = JSON.parse(taskDetiall_Form.data[0][key])
            if (value.value !== '') {
              formResult.push({ key: value.key, value: value.value })
            }
            // if (taskDetiall_Form.data[0][key] !== '') {
            //   const value = JSON.parse(taskDetiall_Form.data[0][key])
            //   if (value.value !== '') {
            //     formResult.push({ key: value.key, value: value.value })
            //   }
            // }
          });
          Object.entries(taskDetiall_Form.data[0]).forEach(([key, value]) => {
            if (key.includes("MultipleSelectValue")) {
              if (value == undefined || value == '') {
                return
              } else {
                // console.log(taskDetiall_Form.data[0][key]);
                const extractedKey = key.split("MultipleSelectValue")[1];
                const index = GetTaskDetailKeywordForm.value.submoduleKeywordEntityResultDtos.findIndex(a => a.keywordId == extractedKey)
                formResult.splice(index, 0, Array.isArray(taskDetiall_Form.data[0][key]) ? { key: extractedKey, value: taskDetiall_Form.data[0][key].join('、') } : { key: extractedKey, value: taskDetiall_Form.data[0][key] })
                //找出多选关键字的位置 然后一一对应
              }
            }
          });
          forms_.taskKeywrodList[0].correctAnswerStr = JSON.stringify(formResult)
          //上面处理form的
          forms_.taskKeywrodList.slice(1).forEach((item, index) => {
            item.type = 1
            let result = '';
            const valueKeys = Object.keys(taskDetiall_Table.data[index]).filter(key => /^value\d+$/.test(key));

            valueKeys.sort((a, b) => {
              const numA = parseInt(a.replace("value", ""));
              const numB = parseInt(b.replace("value", ""));
              return numA - numB;
            });

            valueKeys.forEach(key => {
              const value = taskDetiall_Table.data[index][key];
              if (value !== '') {
                result += value + ";";
              }
            });
            result = result.slice(0, -1);
            Object.entries(taskDetiall_Table.data[index]).forEach(([key, value]) => {
              if (key.includes("MultipleSelectValue")) {
                if (value == undefined || value == '') {
                  return
                } else {
                  const extractedKey = key.split("MultipleSelectValue")[1];
                  const index = GetTaskDetailKeywordTable.value.submoduleKeywordEntityResultDtos.findIndex(a => a.keywordId == extractedKey)
                  let result1 = result.split(';')
                  result1.splice(index, 0, Array.isArray(value) ? value.join("、") : value)
                  result = result1.join(';');
                  //找出多选关键字的位置 然后一一对应
                }
              }
            });
            item.correctAnswerStr = JSON.stringify([{
              key: '',
              value: result
            }])
          });
        }
        if (showForm.value && !showTable.value) {
          forms_.taskKeywrodList[0].type = 2
          const valueKeys = Object.keys(taskDetiall_Form.data[0]).filter(key => /^value\d+$/.test(key));

          valueKeys.sort((a, b) => {
            const numA = parseInt(a.replace("value", ""));
            const numB = parseInt(b.replace("value", ""));
            return numA - numB;
          });
          let formResult = []
          valueKeys.forEach(key => {
            if (taskDetiall_Form.data[0][key] == '') delete taskDetiall_Form.data[0][key]
            if (taskDetiall_Form.data[0][key] == null || taskDetiall_Form.data[0][key] == undefined || taskDetiall_Form.data[0][key] == "") return;
            const value = JSON.parse(taskDetiall_Form.data[0][key])
            if (value.value !== '') {
              formResult.push({ key: value.key, value: value.value })
            }
            // if (taskDetiall_Form.data[0][key] !== '') {
            //   const value = JSON.parse(taskDetiall_Form.data[0][key])
            //   if (value.value !== '') {
            //     formResult.push({ key: value.key, value: value.value })
            //   }
            // }
          });
          Object.entries(taskDetiall_Form.data[0]).forEach(([key, value]) => {
            if (key.includes("MultipleSelectValue")) {
              if (value == undefined || value == '') {
                return
              } else {
                // console.log(taskDetiall_Form.data[0][key]);
                const extractedKey = key.split("MultipleSelectValue")[1];
                const index = GetTaskDetailKeywordForm.value.submoduleKeywordEntityResultDtos.findIndex(a => a.keywordId == extractedKey)
                formResult.splice(index, 0, Array.isArray(taskDetiall_Form.data[0][key]) ? { key: extractedKey, value: taskDetiall_Form.data[0][key].join('、') } : { key: extractedKey, value: taskDetiall_Form.data[0][key] })
                //找出多选关键字的位置 然后一一对应
              }
            }
          });
          forms_.taskKeywrodList[0].correctAnswerStr = JSON.stringify(formResult)
        }
        if (!showForm.value && showTable.value) {
          forms_.taskKeywrodList.forEach((item, index) => {
            item.type = 1
            let result = '';
            const valueKeys = Object.keys(taskDetiall_Table.data[index]).filter(key => /^value\d+$/.test(key));

            valueKeys.sort((a, b) => {
              const numA = parseInt(a.replace("value", ""));
              const numB = parseInt(b.replace("value", ""));
              return numA - numB;
            });
            //正常传给后端的正确答案key value
            valueKeys.forEach(key => {
              const value = taskDetiall_Table.data[index][key];
              if (value !== '') {
                result += value + ";";
              }
            });
            result = result.slice(0, -1);
            // console.log(taskDetiall_Table.data[index]);

            Object.entries(taskDetiall_Table.data[index]).forEach(([key, value]) => {
              if (key.includes("MultipleSelectValue")) {
                if (value == undefined || value == '') {
                  return
                } else {
                  const extractedKey = key.split("MultipleSelectValue")[1];
                  const index = GetTaskDetailKeywordTable.value.submoduleKeywordEntityResultDtos.findIndex(a => a.keywordId == extractedKey)
                  let result1 = result.split(';')
                  // console.log(value);

                  result1.splice(index, 0, Array.isArray(value) ? value.join("、") : value)
                  result = result1.join(';');
                  //找出多选关键字的位置 然后一一对应
                }
              }
            });
            item.correctAnswerStr = JSON.stringify([{
              key: '',
              value: result
            }])
          });
        }
      }
      forms_.taskKeywrodList.forEach(item => {
        item.planId = usetaskPass_.data.planId
      })
      if (forms_.examinationPaperId) {
        forms_.taskKeywrodList.forEach(item => {
          item.taskDetailId = forms.taskDetailId
        })
      }
      if (!forms_.examinationPaperId)
        respone = await TaskDetailSaev(forms_); // 添加
      else respone = await TaskDetailUpdate(forms_); // 修改
      // 重新加载列表内容
      loading.value = true;
      if (respone?.success) {
        ElMessage.success(respone.msg);
        loading.value = false;
        updatePanelVisible.value = false;
        // onSearch(usetaskPass_.data);
        // console.log("ss", usetaskPass_.data)
        emitter.emit("View_Setting", usetaskPass_.data);
        // emitter.emit("View_Details", usetaskPass_.data);

      } else {
        ElMessage.error(respone.msg);
        setTimeout(() => {
          loading.value = false;
        }, 2000);
      }
    });
  }



  // 删除--table
  async function handleDelete(row: { taskDetailId: object; }) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const respone = await TaskDeleteDetail(row.taskDetailId);
      if (respone.success) {
        ElMessage({
          message: respone.msg,
          type: "success"
        });
        emitter.emit("View_Setting", usetaskPass_.data);
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    }).catch(() => { })
  }



  // 操作菜单
  async function GetSubmoduleByModuleId(row: { planId: any; taskId: string; }) {
    const moduleId = row.moduleId;
    const respone = await GetSelectItemBySelectType(moduleId);
    if (respone.success) {
      modelItemList.value = respone.data;
      return
    }
    modelItemList.value = [];
  }

  // 生成相应table 的数据内容
  async function GetTaskAllDetailKeywords(params: string) {
    const respone = await GetTaskDetailById(params);
    if (respone.success) {
      //区分table和form
      if (showForm.value && !showTable.value) {
        let arr1 = respone.data.taskkeywordResultDtos
        let arr2 = taskDetailKeywordInput.value.find(item => item.type == 2).selectKeywordId.split(',')
        arr1.forEach(item => {
          arr2.forEach((el, index) => {
            if (item['value' + Number(index + 1)] !== '') {
              item['value' + Number(index + 1)] = JSON.parse(item['value' + Number(index + 1)])
              item['value' + Number(index + 1)] = item['value' + Number(index + 1)].value
            }
          });
        })
        if (arr1[0]?.multipleSelectValue !== '' && arr1[0]?.multipleSelectValue) {
          const arr = JSON.parse(arr1[0].multipleSelectValue)
          arr.forEach(a => {
            arr1[0]['MultipleSelectValue' + a.key] = a.value.split('、')
          })
        }
        GetTaskAllDetailKeywordsForm.value = arr1
        GetTaskAllDetailKeywordsForm.value = arr1
      }
      if (!showForm.value && showTable.value) {
        GetTaskAllDetailKeywordsTable.value = respone.data.taskkeywordResultDtos;
      }
      if (showForm.value && showTable.value) {
        let arr1 = respone.data.taskkeywordResultDtos.filter(item => item.type == 2)
        let arr2 = taskDetailKeywordInput.value.find(item => item.type == 2).selectKeywordId.split(',')
        arr1.forEach(item => {
          arr2.forEach((el, index) => {
            item['value' + Number(index + 1)] = JSON.parse(item['value' + Number(index + 1)])
            item['value' + Number(index + 1)] = item['value' + Number(index + 1)].value
          });
        })
        if (arr1[0]?.multipleSelectValue !== '' && arr1[0]?.multipleSelectValue) {
          const arr = JSON.parse(arr1[0].multipleSelectValue)
          arr.forEach(a => {
            arr1[0]['MultipleSelectValue' + a.key] = a.value.split('、')
          })
        }
        GetTaskAllDetailKeywordsForm.value = arr1
        GetTaskAllDetailKeywordsTable.value = respone.data.taskkeywordResultDtos.filter(item => item.type == 1)
      }
    }
  }

  onBeforeUnmount(() => {
    emitter.off("closeForm")
  })


  function handleInput() {
    const score = toFixedTwo(forms.score)
    forms.score = score
    // console.log(score);
  }
  // console.log(toFixedTwo(2))
  function toFixedTwo(number) {
    let parsedNumber = parseFloat(number);
    if (Number.isNaN(parsedNumber)) {
      return
    } else if (Number.isInteger(parsedNumber)) {
      return parsedNumber.toString() + ".00";
    } else {
      return parsedNumber.toFixed(2);
    }
  }

  //处理form的联动
  emitter.on("updateSetForm", (newData) => {
    //更换选项
    //先保存一份最原始数据在内存中
    if (!cloneDeepLinkData.value[newData.childKeywordId]) {
      cloneDeepLinkData.value[newData.childKeywordId] = cloneDeep(GetTaskDetailKeywordForm.value.submoduleKeywordEntityResultDtos.find(item => item.keywordId == newData.childKeywordId).selectItemDtos)
    }
    let keyArr = newData.childSelectContent.split(',');
    let result = []
    //找到对应的选项
    cloneDeepLinkData.value[newData.childKeywordId].forEach(item => {
      keyArr.forEach(a => {
        if (item.selectItemId == a) {
          result.push(item)
        }
      })
    })
    GetTaskDetailKeywordForm.value.submoduleKeywordEntityResultDtos.forEach(item => {
      if (item.keywordId == newData.childKeywordId) {
        item.selectItemDtos = result
      }
    })

  })

  return {
    rules,
    forms,
    columns,
    loading,
    dataList,
    _disabled,
    pagination,
    UpedateRef,
    showTable,
    showForm,
    showNoOperation,
    loadingTitle,
    modelItemList,
    updatePanelVisible,
    GetTaskDetailKeywordForm,
    GetTaskDetailKeywordTable,
    GetTaskAllDetailKeywordsForm,
    GetTaskAllDetailKeywordsTable,
    noKeywords,
    GetTaskDetailKeywords_submoduleId,
    handleCurrentChange,
    ClosePanelVisible,
    handleSizeChange,
    DetailsUpdate,
    handleDelete,
    updateTask,
    onSearch,
    handleInput
  };
}
